package com.hcj.springcloud.controller;

import com.alibaba.fastjson.JSONObject;
import com.hcj.springcloud.service.GitHubLookupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@RestController
@RequestMapping("/")
@Slf4j
public class TestThreadController {

    @Value("${server.port}")
    private Integer port;
    @Value("${spring.application.name}")
    private String springApplicationName;

    @Autowired
    private GitHubLookupService gitHubLookupService;

    private final String sysInfo = "current server:[" + springApplicationName + "], and port is [" + port + "], and current time is [" + LocalDateTime.now() + "]";

    @GetMapping("/hi")
    public String sayHi(String name) {
        return "[" + name + "] say hello world! current server:[" + springApplicationName + "], and port is [" + port + "], and current time is [" + LocalDateTime.now() + "]";
    }

    @GetMapping("/github")
    public Object github(String name) throws InterruptedException, ExecutionException {
        long start = System.currentTimeMillis();
        CompletableFuture<String> user = gitHubLookupService.findUser(name);
        CompletableFuture<String> missjin = gitHubLookupService.findUser("missjin");
        CompletableFuture<String> mojombo = gitHubLookupService.findUser("mojombo");

        // Wait until they are all done
        //join() 的作用：让“主线程”等待“子线程”结束之后才能继续运行
        List<CompletableFuture<String>> list = new ArrayList<>();
        CompletableFuture.allOf(user, missjin, mojombo).join();
        // Print results, including elapsed time
        Long exc = (System.currentTimeMillis() - start) / 1000;
        log.info("Elapsed time: " + exc + " seconds");
        log.info("--> {}", user.get());
        log.info("--> {}", missjin.get());
        log.info("--> {}", mojombo.get());
        JSONObject jo = new JSONObject();
        jo.put(name, user.get());
        jo.put("missjin", missjin.get());
        jo.put("mojombo", mojombo.get());
        jo.put("sysInfo", sysInfo);


        return jo;
    }

}
